<script setup lang="ts">
import { computed, reactive, ref } from 'vue';
import { NButton, NCard, NForm, NFormItem, NInput, NTabPane, NTabs } from 'naive-ui';
import { InventoryAuth } from '@/service/api/inventory';
import { useAuthStore } from '@/store/modules/auth';
import { useRouterPush } from '@/hooks/common/router';
import SvgIcon from '@/components/custom/svg-icon.vue';

defineOptions({
  name: 'InventoryLogin'
});

const authStore = useAuthStore();
const { redirectFromLogin } = useRouterPush();

interface FormModel {
  mobile: string;
  code: string;
  username: string;
  password: string;
  token: string;
}

// 登录模式：手机验证码 | 账号密码
const loginMode = ref<'phoneCode' | 'phonePwd'>('phonePwd');
const loading = ref(false);
const codeLoading = ref(false);
const countdown = ref(0);

// 表单数据
const model: FormModel = reactive({
  mobile: '',
  code: '',
  username: '18888888888',
  password: '123456',
  token: ''
});

// 验证码倒计时文本
const codeText = computed(() => {
  if (countdown.value > 0) {
    return `${countdown.value}s后重新获取`;
  }
  return '获取验证码';
});

// 获取验证码
async function getCode() {
  if (!model.mobile || !/^1[3-9]\d{9}$/.test(model.mobile)) {
    window.$message?.error('请输入正确的手机号');
    return;
  }

  if (countdown.value > 0) {
    window.$message?.warning('请等待倒计时结束');
    return;
  }

  try {
    codeLoading.value = true;
    const response = await InventoryAuth.sendCode(model.mobile);

    // 处理验证码响应数据
    let tokenData: any;

    if (response.error && response.response?.data) {
      // HTTP 200 但被axios标记为错误，实际数据在 response.response.data
      tokenData = response.response.data;
    } else {
      // 正常响应
      tokenData = response;
    }

    if (tokenData && tokenData.data) {
      model.token = tokenData.data;
      window.$message?.success('发送成功');
      startCountdown();
    } else {
      window.$message?.error(tokenData?.msg || '获取验证码失败');
    }
  } catch (error: any) {
    window.$message?.error(error?.message || '获取验证码失败');
  } finally {
    codeLoading.value = false;
  }
}

// 开始倒计时
function startCountdown() {
  countdown.value = 60;
  const timer = setInterval(() => {
    countdown.value -= 1;
    if (countdown.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
}

// 登录提交
async function handleSubmit() {
  try {
    loading.value = true;

    if (loginMode.value === 'phoneCode') {
      // 手机验证码登录
      if (!model.token) {
        window.$message?.error('请先获取验证码');
        return;
      }

      const response = await InventoryAuth.loginByMobileCode(model.mobile, model.code, model.token);
      // 直接处理响应，无论是否标记为error
      await handleLoginSuccess(response);
    } else {
      // 账号密码登录
      const response = await InventoryAuth.loginByUserName(model.username, model.password);
      // 直接处理响应，无论是否标记为error
      await handleLoginSuccess(response);
    }
  } catch (error: any) {
    window.$message?.error(error?.message || '登录失败');
  } finally {
    loading.value = false;
  }
}

// 处理登录成功
async function handleLoginSuccess(response: any) {
  try {
    console.log('完整登录响应:', response);

    // 处理axios误判为错误的情况：HTTP 200但data为null，实际数据在response.response.data
    let loginData;

    if (response.error && response.response?.data) {
      // axios标记为错误，但实际是成功响应，数据在response.response.data
      loginData = response.response.data;
      console.log('从错误响应中提取的成功数据:', loginData);
    } else if (response.data) {
      // 正常响应路径
      loginData = response.data;
    } else {
      loginData = response;
    }

    // 检查基本的登录数据结构
    if (!loginData) {
      window.$message?.error('登录响应为空');
      return;
    }

    // 验证这确实是成功响应（库存助手API：code=1表示成功）
    if (loginData.code !== 1) {
      window.$message?.error(loginData.msg || '登录失败');
      return;
    }

    // 检查是否有token（登录成功的标志）
    if (!loginData.token) {
      window.$message?.error('登录失败：缺少访问令牌');
      return;
    }

    // 检查用户数据
    if (!loginData.data || (!loginData.data.userName && !loginData.data.name)) {
      window.$message?.error('登录失败：缺少用户信息');
      return;
    }

    // 构建标准化的登录结果对象
    const standardizedLoginResult = {
      token: loginData.token,
      data: {
        userId: loginData.data.userId || loginData.data.objectId || loginData.data.userName,
        userName: loginData.data.userName || loginData.data.name,
        // 保留其他用户数据
        ...loginData.data
      },
      rights: loginData.rights || {},
      setting: loginData.setting || {}
    };

    console.log('标准化后的登录结果:', standardizedLoginResult);

    // 使用库存助手专用的登录方法
    const success = await authStore.loginByInventoryToken(standardizedLoginResult);

    if (success) {
      window.$notification?.success({
        title: '登录成功',
        content: `欢迎回来，${standardizedLoginResult.data.userName}！`,
        duration: 3000
      });

      // 跳转到首页
      await redirectFromLogin();
    } else {
      window.$message?.error('登录状态设置失败，请重试');
    }
  } catch (error) {
    console.error('登录处理异常:', error);
    window.$message?.error('登录过程出现异常，请重试');
  }
}
</script>

<template>
  <div class="inventory-login w-full">
    <!-- 登录表单 -->
    <NTabs v-model:value="loginMode" type="segment" animated size="large" class="mb-6">
      <NTabPane name="phonePwd" tab="账号密码">
        <NForm ref="formRef" :model="model" size="large" label-placement="left">
          <NFormItem label="用户名" path="username">
            <NInput v-model:value="model.username" placeholder="请输入用户名" clearable>
              <template #prefix>
                <SvgIcon icon="ant-design:user-outlined" class="text-icon" />
              </template>
            </NInput>
          </NFormItem>

          <NFormItem label="密码" path="password">
            <NInput v-model:value="model.password" type="password" show-password-on="click" placeholder="请输入密码">
              <template #prefix>
                <SvgIcon icon="ant-design:lock-outlined" class="text-icon" />
              </template>
            </NInput>
          </NFormItem>

          <div class="w-full pt-16px">
            <NButton :loading="loading" type="primary" size="large" class="w-full rounded-8px" @click="handleSubmit">
              登录
            </NButton>
          </div>
        </NForm>
      </NTabPane>

      <NTabPane name="phoneCode" tab="手机验证码">
        <NForm ref="formRef" :model="model" size="large" label-placement="left">
          <NFormItem label="手机号" path="mobile">
            <NInput v-model:value="model.mobile" placeholder="请输入手机号" :maxlength="11" clearable>
              <template #prefix>
                <SvgIcon icon="ant-design:mobile-outlined" class="text-icon" />
              </template>
            </NInput>
          </NFormItem>

          <NFormItem label="验证码" path="code">
            <div class="w-full flex gap-12px">
              <NInput v-model:value="model.code" placeholder="请输入验证码" :maxlength="6" class="flex-1">
                <template #prefix>
                  <SvgIcon icon="ant-design:safety-certificate-outlined" class="text-icon" />
                </template>
              </NInput>
              <NButton :loading="codeLoading" :disabled="countdown > 0" @click="getCode">
                {{ codeText }}
              </NButton>
            </div>
          </NFormItem>

          <div class="mb-16px text-center">
            <span class="text-12px text-gray-500">未注册手机号验证后将自动创建账号</span>
          </div>

          <div class="w-full">
            <NButton :loading="loading" type="primary" size="large" class="w-full rounded-8px" @click="handleSubmit">
              登录
            </NButton>
          </div>
        </NForm>
      </NTabPane>
    </NTabs>

    <!-- 登录提示 -->
    <div class="mt-24px">
      <NCard class="rounded-8px" :bordered="false" embedded>
        <div class="mb-8px flex items-center gap-8px text-12px text-primary">
          <SvgIcon icon="ant-design:info-circle-outlined" />
          <span class="font-medium">使用说明</span>
        </div>
        <div class="space-y-4px">
          <div class="flex items-center gap-8px text-11px text-gray-600">
            <span class="h-4px w-4px rounded-full bg-primary"></span>
            <span>员工请使用账号密码登录</span>
          </div>
        </div>
      </NCard>
    </div>
  </div>
</template>

<style scoped>
.inventory-login {
  width: 100%;
}

.text-icon {
  font-size: 16px;
  color: #8e8e93;
}
</style>
